<template>
  <!-- 新建编辑备件组件 -->
  <div class="form-sparepart">
    <!-- 添加按钮 S -->
    <el-button
      class="add-subform-btn"
      icon="el-icon-plus"
      @click="(visible = true), handleClickAdd()"
    >
    {{$t('common.base.addModule', {module:''})}}
    </el-button>
    <!-- 添加按钮 E -->

    <!-- 备件表单表格 S -->
    <el-table
      v-table-style
      :data="dataList"
      header-row-class-name="common-list-table-header__v2"
      border
    >
      <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.field}_${index}`"
        :label="column.displayName"
        :min-width="column.minWidth || '108px'"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{
            $formatFormField(column, scope.row)
          }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('common.base.operation')" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="handleClickDelete(scope.$index)"
          >
          {{$t('common.base.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 备件表单表格 E -->

    <!-- 字表单弹框 S -->
    <base-modal
      :show.sync="visible"
      :title="title"
      width="600px"
      append-to-body
    >
      <div class="sparepart-model">
        <form-builder
          v-if="visible"
          ref="form"
          :fields="subFields"
          :value="form"
          @update="update"
        >
          <template slot="name" slot-scope="{ field, value }">
            <form-item :label="field.displayName">
              <biz-form-remote-select
                :field="field"
                v-model="selectedSparepart"
                :remote-method="searchSparepart"
                @input="updateSparepart"
                :placeholder="$t('common.placeholder.select')"
              >
                <div
                  class="part-template-option"
                  slot="option"
                  slot-scope="{ option }"
                >
                  <h3>{{ option.name }}</h3>
                  <div class="part-template-option-text">
                    <label>{{$t('common.form.preview.subSparePart.label1')}}</label>
                    <span>{{ option.serialNumber }}</span>
                  </div>
                </div>
              </biz-form-remote-select>
            </form-item>
          </template>
        </form-builder>
      </div>

      <div slot="footer">
        <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="handleClickSubmit"
          >{{$t('common.base.submit')}}</el-button
        >
      </div>
    </base-modal>
    <!-- 字表单弹框 E -->
  </div>
</template>

<script>
/* mixin */
import FormMixin from '@src/component/form/mixin/form';
/* util */
import * as FormUtil from '@src/component/form/util';

export default {
  name: 'form-sparepart-build',
  mixins: [FormMixin],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      dataList: this.value || [],
      visible: false,
      form: {},
      selectedSparepart: [], // 当前选中的备件
    };
  },
  computed: {
    // 标题
    title() {
      return this.$t('common.base.addModule', {module:this.$t('common.base.sparePart')});
    },
    // 表头数据
    columns() {
      return this.field?.subFormFieldList || [];
    },
    subFields() {
      let fields = this.field?.subFormFieldList || [];
      fields.forEach(item => {
        if (item.fieldName == 'name') {
          item.isNull = 0
          item.formType = 'select'
        } else {
          item.isNull = 1;
        }
      });
      return fields;
    },
  },
  watch: {
    value(newValue) {
      this.dataList = newValue || [];
    },
  },
  methods: {
    // 点击添加
    handleClickAdd() {
      this.form = FormUtil.initialize(this.subFields, {});
      this.selectedSparepart = [];
    },
    // 删除备件
    handleClickDelete(index) {
      this.dataList.splice(index, 1);
      this.inputForValue(this.dataList);
    },
    // 更新表单数据
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;
      this.$set(this.form, fieldName, newValue);
    },
    // 获取备件
    async fetchSparepartList(selectParams) {
      let params = {
        keyWord: selectParams.keyword,
        pageNum: selectParams.pageNum,
        pageSize: 50,
      };

      try {
        let res = await this.$http.post('/partV2/category/listData', params);
        if (!res || !res.list) return;

        res.list = res.list.map(item =>
          Object.freeze({
            label: item?.name || '',
            value: item?.id || '',
            ...item,
          })
        );

        res.pageNum = params.page;

        return res;
      } catch (error) {
        console.warn('etchSparepartList -> error', error);
      }
    },
    // 搜索备件
    async searchSparepart(params = {}) {
      return this.fetchSparepartList(params);
    },

    // 更新备件数据
    updateSparepart(value) {
      let newValue = value[0];
      this.subFields.map(field => {
        let fieldName = field.fieldName;
        let fieldVal = newValue[fieldName]; // 表单的值

        this.form[fieldName] = fieldVal;
      });

      this.form['id'] = newValue.id;
    },

    // 提交
    async handleClickSubmit() {
      // 校验表单必填项
      const validateRes = await this.$refs.form.validate(false);
      if (!validateRes) return;
      
      // 校验备件是否添加重复
      let isExit = (this.dataList || []).some(v => v?.id == this.form.id);
      if (isExit) return this.$message.warning(this.$t('common.base.tip.notAddRepeatedlyModule2', {module:this.$t('common.base.sparePart')}));

      this.dataList.push(this.form);
      this.inputForValue(this.dataList);
      this.visible = false;
      this.form = {};
    },
  },
};
</script>
<style lang="scss" scoped>
.form-sparepart {
  .add-subform-btn {
    color: $color-primary;
    border-color: #b8eded;
    background-color: $color-primary-light-1;
    margin-bottom: 12px;
    &:hover {
      background: $color-primary-light-6;
      border-color: $color-primary-light-6;
      color: #fff;
    }
  }
}
.part-template-option {
  font-size: 12px;
  line-height: 14px;
  padding: 10px 0;
}
.sparepart-model {
  min-height: 360px;
  ::v-deep .form-item label {
    width: 80px;
  }
}
</style>
